package org.hdlh.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.hdlh.core.Header;
import org.hdlh.core.RpcProtocol;
import org.hdlh.serial.ISerializer;
import org.hdlh.serial.SerializerManager;



/**
 * 编码器
 */
@Slf4j
public class RpcCodec extends MessageToByteEncoder<RpcProtocol<Object>> {


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcProtocol<Object> msg, ByteBuf out) throws Exception {
        log.info("begin rpc encoder");
        Header header = msg.getHeader();
        out.writeShort(header.getMagic());
        out.writeByte(header.getSerialType());
        out.writeByte(header.getReqType());
        out.writeLong(header.getRequestId());
        ISerializer iSerializer = SerializerManager.getSerializer(header.getSerialType());
        byte[] data = iSerializer.serialize(msg.getContent());
        out.writeInt(data.length);
        out.writeBytes(data);
    }
}
